package com.example.NearByLocation;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import org.json.JSONException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/26.
 */
public class PoiListActivity extends FragmentActivity {
    private Button back_toThirdMenu_bt;
    private Button down_bt;
    private TextView scale_textview;
    private TextView poiList_textview;
    private String keyWord;
    private int radius;
    private BaiduMap baiduMap;
    private List<JsonData> list;
    private ListView poiList_list;
    private double longi;
    private double leni;
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    boolean isFirstLoc = true;
    private Button poiList_bt;
    private Button poiList_map;
    private RelativeLayout map_rela;
    private Button poiRefresh_bt;
    int a = 10;
    private int page = 1;
    private Button current_bt;
    private List<Marker> markerList;
    private InfoWindow mInfoWindow;
    private int pageChange=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.poilist);

        SharedPreferences pref = getSharedPreferences("ServiceName", MODE_PRIVATE);
        final String thirdName = pref.getString("thirdName", "aa");
        keyWord = thirdName;

        back_toThirdMenu_bt = (Button) findViewById(R.id.back_toThirdMenu_bt);
        down_bt = (Button) findViewById(R.id.down_bt);
        scale_textview = (TextView) findViewById(R.id.scale_textview);
        poiList_textview = (TextView) findViewById(R.id.poiList_textview);

        baiduMap = ((SupportMapFragment) (getSupportFragmentManager()
                .findFragmentById(R.id.map))).getBaiduMap();
        getCurrentLoc();
        poiList_textview.setText(thirdName);
        back_toThirdMenu_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        down_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAlertD();
            }
        });
//  定位
        LocationManager locationManager = new LocationManager(this, poiList_textview);
        final LatLng currentLat = locationManager.currentLat;
        if (currentLat == null) {
            Toast.makeText(PoiListActivity.this, "没有定到位置", Toast.LENGTH_SHORT).show();
        } else {
            longi = currentLat.longitude;
            leni = currentLat.latitude;


//        poISearchManager.makePoi(this,baiduMap,currentLat,keyWord,radius);
//        获取到poi点详情列表
            radius = 3000;
            getData(keyWord, radius, longi, leni,page);
            //图标点击事件
            baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(final Marker marker) {
                    Button button = new Button(getApplicationContext());
                    button.setBackgroundResource(R.drawable.popup);
                    for (int i = 0; i < markerList.size(); i++) {
                        if (marker == markerList.get(i)) {
                            final String name = list.get(i).getName();
                            final String address = list.get(i).getAdd();
                            final String distance = list.get(i).getDistance();
                            final String phoneNum = list.get(i).getPhoneNo();
                            final String longi1 = list.get(i).getLongi();
                            final String leni1 = list.get(i).getLeni();
                            button.setText(list.get(i).getName());
                            Log.d("listget", list.get(i).getName());
                            button.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(PoiListActivity.this, RouteLineActivity.class);
                                    intent.putExtra("name", name);
                                    intent.putExtra("address", address);
                                    intent.putExtra("distance", distance);
                                    intent.putExtra("phoneNum", phoneNum);
                                    intent.putExtra("longi1", longi1);
                                    intent.putExtra("leni1", leni1);
                                    startActivity(intent);
                                    baiduMap.hideInfoWindow();
                                }
                            });
                        }
                    }
                    LatLng ll = marker.getPosition();
                    mInfoWindow = new InfoWindow(button, ll, -47);
                    baiduMap.showInfoWindow(mInfoWindow);
                    return true;
                }
            });

        }
        poiList_bt = (Button) findViewById(R.id.poiList_bt);
        poiList_map = (Button) findViewById(R.id.poiList_map);
        map_rela = (RelativeLayout) findViewById(R.id.map_rela);
        poiList_list = (ListView) findViewById(R.id.poiList_list);
        poiRefresh_bt = (Button) findViewById(R.id.poiRefresh_bt);
//切换图片
        poiList_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                poiList_bt.setVisibility(View.INVISIBLE);
                poiList_map.setVisibility(View.VISIBLE);
                poiList_list.setVisibility(View.GONE);
                map_rela.setVisibility(View.VISIBLE);

            }
        });
        poiList_map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                poiList_map.setVisibility(View.INVISIBLE);
                poiList_bt.setVisibility(View.VISIBLE);
                map_rela.setVisibility(View.GONE);
                poiList_list.setVisibility(View.VISIBLE);
            }
        });
        poiRefresh_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData(keyWord, radius, longi, leni,page);
            }
        });
        current_bt = (Button) findViewById(R.id.current_bt);
        current_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MapStatusUpdate u = MapStatusUpdateFactory
                        .newLatLng(currentLat);
                baiduMap.setMapStatus(u);

            }
        });
    }


    private void getAlertD() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(PoiListActivity.this);
        builder.setTitle("选择范围");
        builder.setIcon(R.drawable.ic_arrow_down);
        final String[] item = {"1000", "2000", "3000", "4000", "5000"};
        String currentNumber = scale_textview.getText().toString();
        int itemNumber = getItemNumber(currentNumber);
        builder.setSingleChoiceItems(item, itemNumber, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                scale_textview.setText("范围:" + item[which] + "m内");
                radius = Integer.parseInt(item[which]);
                dialog.dismiss();
             }
        });
        builder.show();
    }

    private int getItemNumber(String str) {
        if (str.equals("范围:1000m内")) {
            return 0;
        } else if (str.equals("范围:2000m内")) {
            return 1;
        } else if (str.equals("范围:3000m内")) {
            return 2;
        } else if (str.equals("范围:4000m内")) {
            return 3;
        } else if (str.equals("范围:5000m内")) {
            return 4;
        }
        return 0;
    }

    class PoiListAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            JsonData jsonData = (JsonData) getItem(position);
            View view;
            if (convertView == null) {
                view = getLayoutInflater().inflate(R.layout.poilist_item, parent, false);
            } else {
                view = convertView;
            }
            TextView poiName_text = (TextView) view.findViewById(R.id.poiName_text);
            TextView poiAddress_text = (TextView) view.findViewById(R.id.poiAddress_text);
            TextView poiDistance_text = (TextView) view.findViewById(R.id.poiDistance_text);

            poiName_text.setText(jsonData.getName());
            poiAddress_text.setText(jsonData.getAdd());

            if (Integer.parseInt(jsonData.getDistance()) <= 1000) {
                poiDistance_text.setText(jsonData.getDistance() + "m");
            } else if (Integer.parseInt(jsonData.getDistance()) > 1000) {
                double a = Integer.parseInt(jsonData.getDistance()) / 1000;
                poiDistance_text.setText(a + "km");
            }
            return view;
        }
    }

    public void getData(final String keyWord, final int range, final double longi, final double leni,final int page) {
        final ProgressDialog dialog = new ProgressDialog(PoiListActivity.this);
        dialog.setMessage("正在获取。。。。。");
        dialog.show();
        AsyncTask<String, String, Integer> asyncTask = new AsyncTask<String, String, Integer>() {
            @Override
            protected Integer doInBackground(String... params) {
                HttpClientManager httpClientManager = new HttpClientManager();
                try {
                    list = new ArrayList<JsonData>();
                    list = httpClientManager.getData(keyWord, range, longi, leni,page);
                    Log.d("josn", list.size() + " ");
                } catch (IOException e) {
                    return 1;
                } catch (JSONException e) {
                    return 2;
                }
                return 0;
            }

            @Override
            protected void onPostExecute(Integer integer) {
                if (integer == 1) {
                    Toast.makeText(PoiListActivity.this, "网络通道阻塞", Toast.LENGTH_SHORT).show();
                } else if (integer == 2) {
                    Toast.makeText(PoiListActivity.this, "服务器异常", Toast.LENGTH_SHORT).show();
                } else {
                    poiRefresh_bt.setVisibility(View.VISIBLE);
                    poiList_bt.setVisibility(View.VISIBLE);
                    dialog.dismiss();
                    //显示列表
                    final PoiListAdapter poiListAdapter = new PoiListAdapter();
                    final View view = getLayoutInflater().inflate(R.layout.addmorebt, null, false);
                    poiList_list = (ListView) findViewById(R.id.poiList_list);
                    if (list.size() > 9) {
                        if (poiList_list.getFooterViewsCount() == 0) {
                            poiList_list.addFooterView(view);
                        }
                        final Button addMoreButton = (Button) findViewById(R.id.addMoreButton);
                        addMoreButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pageChange++;
                                getData(keyWord, radius, longi, leni,pageChange);
//                                if(list.size()==10){
                                 poiListAdapter.notifyDataSetChanged();
//                                }
//                                else{
//                                    poiList_list.removeFooterView(view);
//                                    poiListAdapter.notifyDataSetChanged();

//                                }
                            }

                        });
                    }
                    if(list.size()>0){
                        poiList_list.setAdapter(poiListAdapter);
                    }
                    poiList_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            poiList_bt.setVisibility(View.INVISIBLE);
                            poiList_map.setVisibility(View.VISIBLE);
                            poiList_list.setVisibility(View.GONE);
                            map_rela.setVisibility(View.VISIBLE);
                            JsonData jsonData = list.get(position);
                            iconShow(jsonData);
                        }
                    });
                   //  扎针了
                    markerList = new ArrayList<Marker>();
                    MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
                    baiduMap.setMapStatus(msu);
                    for (int i = 0; i < list.size(); i++) {
                        JsonData data = list.get(i);
                        LatLng lal = new LatLng(Double.parseDouble(data.getLeni()), Double.parseDouble(data.getLongi()));
                        makeMark(lal, baiduMap);
                    }
//                    zoomTo();
                }
            }
        };
        asyncTask.execute();
    }

    private void iconShow(JsonData jsonData) {
        Button button = new Button(getApplicationContext());
        button.setBackgroundResource(R.drawable.popup);
        LatLng latLng = null;
        for (int i = 0; i < list.size(); i++) {
            if (jsonData.getName().equals(list.get(i).getName())) {
                final String name = list.get(i).getName();
                final String address = list.get(i).getAdd();
                final String distance = list.get(i).getDistance();
                final String phoneNum = list.get(i).getPhoneNo();
                final String longi1 = list.get(i).getLongi();
                final String leni1 = list.get(i).getLeni();
                button.setText(list.get(i).getName());
                latLng = new LatLng(Double.parseDouble(list.get(i).getLeni()), Double.parseDouble(list.get(i).getLongi()));
                Log.d("listget", list.get(i).getName());
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(PoiListActivity.this, RouteLineActivity.class);
                        intent.putExtra("name", name);
                        intent.putExtra("address", address);
                        intent.putExtra("distance", distance);
                        intent.putExtra("phoneNum", phoneNum);
                        intent.putExtra("longi1", longi1);
                        intent.putExtra("leni1", leni1);
                        startActivity(intent);
                        baiduMap.hideInfoWindow();
                    }
                });
            }
        }
        mInfoWindow = new InfoWindow(button, latLng, -47);
        baiduMap.showInfoWindow(mInfoWindow);
    }

    public void makeMark(LatLng currentLal, BaiduMap mBaiduMap) {
        BitmapDescriptor bd = BitmapDescriptorFactory.fromResource(R.drawable.ic_loc_normal);
        OverlayOptions oob = new MarkerOptions().position(currentLal).icon(bd).zIndex(7);
        markerList.add((Marker) mBaiduMap.addOverlay(oob));
        Log.d("marklist", markerList.size() + "");
    }
    private  void zoomTo(){
          Double[] len=new Double[list.size()];
          Double[] lon=new Double[list.size()];
        for (int i = 0; i <list.size() ; i++) {
             len[i]=Double.parseDouble(list.get(i).getLeni());
             lon[i]=Double.parseDouble(list.get(i).getLongi());
        }
        for (int j = 0; j <len.length ; j++) {
            if(len[j]>len[j+1]){
                len[j+1]=len[j];
            }
        }
        for (int x = 0; x<len.length ; x++) {
            if(len[x]>len[x+1]){
                len[x+1]=len[x];
            }
        }

    }
    private void getCurrentLoc() {
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        mCurrentMarker = null;
        baiduMap
                .setMyLocationConfigeration(new MyLocationConfiguration(
                        mCurrentMode, true, null));

        baiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();

            baiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                baiduMap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }
}
